package fr.ginvest.implementation;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.ginvest.entity.Club;
import fr.ginvest.interfaces.ClubFacadeRemote;

/**
 * Session Bean implementation class ClubFacade
 */
@Stateless
public class ClubFacade implements ClubFacadeRemote {
	@PersistenceContext
	protected EntityManager entityMgr;
	
	public ClubFacade() {
	}	

	public ClubFacade(EntityManager entityMgr) {
		this.entityMgr = entityMgr;
	}

	@Override
	public Club addClub(Club c) {
		entityMgr.persist(c);
    	return c;
	}

	@Override
	public Club findClubById(int id) {
		//return entityMgr.find(Club.class, id);
		final String queryString = "select c from Club c left join fetch c.amis where c.id=?1";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter(1, id);
		return (Club)query.getSingleResult();
	}

	@Override
	public Club updateClub(Club c) {
		return entityMgr.merge(c);
	}

	@Override
	public void deleteClub(Club c) {
		entityMgr.remove(c);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Club> listClubs() {
		return entityMgr.createQuery("SELECT c FROM Club c").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Club> findClubByName(String name) {
		final String queryString = "select c from Club as c where c.nom like %?1%";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter(1, name);
		return query.getResultList();
	}
}
